/*
 * @Description: 用户状态管理，包括用户信息、登录状态和菜单权限
 * @Author: SongWenJie
 * @LastEditors: SongWenJie
 * @Date: 2024-07-19 16:40:45
 * @LastEditTime: 2024-07-20 00:01:01
 */
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { logoutApi } from "../api/user";

// 初始状态
const initialState = {
  userName: "",
  role: "",
  menus: [],
};

// 创建异步 action 用于处理登出逻辑
export const logout = createAsyncThunk(
  "user/logout",
  async (_, { rejectWithValue }) => {
    try {
      // 调用登出 API
      await logoutApi();
      return;
    } catch (error) {
      // 如果登出失败，返回错误信息
      return rejectWithValue(error.response.data);
    }
  }
);

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    // 设置用户信息
    setUserInfo: (state, action) => {
      state.userId=action.payload.userId
      state.userName = action.payload.userName
      state.role = action.payload.role
      state.menus = action.payload.menus
      // 将菜单信息存储到本地存储
      localStorage.setItem("menus", JSON.stringify(action.payload.menus));
    },
    // 清除用户信息
    clearUserInfo: (state) => {
      state.userName = "";
      state.role = "";
      state.menus = [];
      // 从本地存储中移除菜单信息
      localStorage.removeItem("menus");
    },
  },
  extraReducers: (builder) => {
    builder
      // 处理登出成功的情况
      .addCase(logout.fulfilled, (state) => {
        state.userName = "";
        state.role = "";
        state.menus = [];
        // 清除本地存储中的相关信息
        localStorage.removeItem("menus");
        localStorage.removeItem("token");
      })
      // 处理登出失败的情况
      .addCase(logout.rejected, (state, action) => {
        // 可以在这里处理退出登录失败的情况，比如显示错误消息
        console.error("Logout failed:", action.payload);
      });
  },
});

// 导出 actions
export const { setUserInfo, clearUserInfo } = userSlice.actions;

// 导出 reducer
export default userSlice.reducer;
